package wassalt.Services;

import static wassalt.Utils.User.loadUser;

import java.net.URLEncoder;
import java.util.Date;



import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import wassalt.Utils.User;
import wassalt.client.R;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

public class GpsService extends Service {

	static final String TAG = "GpsService";
	Thread triggerService;
	LocationManager lm;
	GPSListener myLocationListener;
	static double latitude = -91; //invalid point
	static double longitude = -181;//invalid point

	@Override
	public void onStart(Intent intent, int startId) {
		Log.i(TAG, "I am alive-GPS!");
		// we place the slow work of the service in its own thread so the
		// response we send our caller who run a "startService(...)" method
		// gets a quick OK from us.
		setLocationOnStart();
		triggerService = new Thread(new Runnable() {
			public void run() {
				try {
					Looper.prepare();

					// This listener will catch and disseminate location updates
					myLocationListener = new GPSListener();
					long minTime = 1; // frequency update: 10 seconds
					float minDistance = 0.1f; // frequency update: 50 meter
					lm.requestLocationUpdates(
							// request GPS updates
							LocationManager.NETWORK_PROVIDER, minTime,
							minDistance, myLocationListener);
					Looper.loop();
				} catch (Exception e) {
					Log.e("GpsService", e.getMessage());
				}
			}// run
		});
		triggerService.start();

	}

	void setLocationOnStart() {
		// try to get your GPS location using the LOCATION.SERVIVE
		// provider
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		try {
			Location lastKnownLocation = lm
					.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			latitude = lastKnownLocation.getLatitude();
			longitude = lastKnownLocation.getLongitude();
		} catch (NullPointerException e) {
			Log.e(TAG, e.toString());
		}
	}

	private class GPSListener implements LocationListener {
		public void onLocationChanged(Location location) {
			try {
				// capture location data sent by current provider
				Log.e("GPSListener", "Location changed");
				User user = loadUser(getApplicationContext());
				if (user == null || user.getPhone() == null)
					return;
				latitude = location.getLatitude();
				longitude = location.getLongitude();
				Log.e("GPSListener", latitude + " " + longitude);
				DefaultHttpClient client = new DefaultHttpClient();
				String PATH = "/GPS/updateUserLocation?phone="
						+ user.getPhone() + "&longitude=" + longitude
						+ "&latitude=" + latitude+"&cuTime="+URLEncoder.encode(new Date().toLocaleString(),"UTF-8" );
				Log.e("GPSListenerHost", getString(R.string.server_url) + PATH);
			
				HttpResponse resp = client.execute(new HttpGet(
						getString(R.string.server_url) + PATH));
				Log.e("GPSListener", EntityUtils.toString(resp.getEntity()));
			} catch (Exception e) {
				e.printStackTrace();
				Log.e("GPSListener", e.getMessage());
			}
		}

		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub
			Log.e("Listener", "onProviderDisabled");
		}

		@Override
		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub
			Log.e("Listener", "onProviderEnabled");

		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub
			Log.e("Listener", "onStatusChanged");
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * Returns the last seen location
	 * 
	 * @author loai
	 */
	public static double[] getCurrentLocation() {
		return new double[] { latitude, longitude };
	}

	/**
	 * Class to obtain an instance of the current running service
	 * 
	 * @author Dalia
	 * 
	 */
	public class LocalBinder extends android.os.Binder {

		public GpsService getService() {

			return GpsService.this;

		}

	}

}
